
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

var app = angular.module('deepDRapp', ['ngRoute', 'ngFileUpload', 'smart-table']);
// Define the `PhoneListController` controller on the `phonecatApp` module
app.controller('appController', function appController($scope) {
    $scope.name = 'default name2';
    $scope.menuItem = 'login';
    $scope.debug = false;
    $scope.token = '';
    $scope.set_token = function (token) {
        $scope.token = token;
        setCookie('token',token,7);
    };
    $scope.set_menu_item = function(manu_item){
        if($scope.token ===''){
            $scope.menuItem = 'login';
            return
        }
        $scope.menuItem = manu_item;
    };
    $scope.init = function () {
        console.log('called');
        tk = getCookie('token');
        if (tk !== ''){
            $scope.token = tk;
            $scope.set_menu_item('list')
        }
        console.log(tk)
    }
});

/**
 * pictures are structures like this:
 * {
 *      url : set when finished
 *      id : set when finished
 *      percentage:
 *      which_eye: right/left
 * }
 */
app.controller('newImage', ['$scope', 'Upload', '$timeout', '$http',
    function ($scope, Upload, $timeout, $http) {
        $scope.init = function () {
            $scope.patient = {
                name: null,
                gender: 'male',
                age: null,
                eye_sight: null,
                id: 0,
                pictures: [],
                reports_ready: true,
                submitted: false,
                diag_finished: false,

                addpic: function (file) {
                    var x = {
                        // server returned info
                        url: '',
                        id: 0,
                        // file info
                        which_eye: 'right',
                        file: file,
                        // upload info
                        percentage: 0,
                        finished: false,
                        error: false,
                        started: false,
                        filename: '',
                        result: {
                            ready: false
                        }
                    };

                    this.pictures.push(x);
                    $scope.upload(x)
                }
            };
            $scope.refreshIntervalId = 1;
            $scope.diagnose_nready = true;
        };
        $scope.init();

        $scope.get_diagnose_result = function (file) {
            if (file.result && file.result.ready) {
                return true
            }
            console.log('get result for ' + file.id);
            if (!file.id || file.id <= 0) {
                return false
            }
            $http({
                method: 'GET',
                url: '/api/get_single_image/' + file.id
            }).then(function (response) {
                // success call back
                console.log('successful request');
                console.log(response);
                file.result = response.data.result;
                file.result.ready = response.data.result.ready;
                file.filename = response.data.filename;
            }, function (response) {
                console.error(response)
            });
        };

        $scope.delPic = function (index) {
            if (index > $scope.patient.pictures.length || index < 0) {
                console.error('Error insex of ' + index);
                return;
            }
            console.log('deleting ' + index + 'th picture');
            $scope.patient.pictures.splice(index, 1);
        };

        $scope.new_patient = function () {
            console.log('add patient');
            for (var i = 0; i < $scope.patient.pictures.length; i++) {
                $scope.patient.pictures[i].result.ready = false;
            }
            $http({
                method: 'POST',
                url: '/api/add_patient',
                headers: {
                    'Content-Type': 'application/json'
                },
                data: $scope.patient
            }).then(function (response) {
                // success call back
                console.log('successful request');
                console.log(response);
                // $scope.init();
            }, function (response) {
                console.log(response)
            });
            $scope.submitted = true;
            // start watch function
            $scope.refreshIntervalId = setInterval(function () {
                var r = false;
                for (var i = 0; i < $scope.patient.pictures.length; i++) {
                    r = r || !$scope.get_diagnose_result($scope.patient.pictures[i]);
                }
                $scope.diagnose_nready = r;
                if (!r) {
                    clearInterval($scope.refreshIntervalId);
                }
            }, 2000)
        };
        $scope.$watch('files', function () {
            console.log('files change');
            if (!$scope.files) {
                return
            }
            for (var i = 0; i < $scope.files.length; i++) {
                $scope.patient.addpic($scope.files[i]);
            }
        });
        $scope.log = '';

        $scope.upload = function (f) {
            if (!f || f.started || f.finished || !f.file) {
                console.error('error when trying to upload ' + f);
                return;
            }
            console.info('uploading file ' + f.file.name);
            f.started = true;
            var file = f.file;
            if (!file.$error) {
                Upload.upload({
                    url: '/api/upload',
                    data: f
                }).then(function (resp) {
                    $timeout(function () {
                        $scope.log = 'file: ' +
                            resp.config.data.file.name +
                            ', Response: ' + JSON.stringify(resp.data) +
                            '\n' + $scope.log;
                        f.id = resp.data.id;
                        f.url = resp.data.url;
                        f.finished = true;
                    });
                }, null, function (evt) {
                    f.percentage = parseInt(100.0 * evt.loaded / evt.total);
                });
            }
        };
        $scope.update_change = function () {
            alert('修改已提交')
        };
        // init
        if ($scope.debug) {
            // $scope.patient.addpic();
        }
    }]);

app.controller('basicsCtrl', ['$scope', '$timeout', '$http', function (scope, $timeout, $http) {
    scope.rowCollection = [];
    scope.renew = function (recall_func) {
        console.log('updata');
        $http({
            method: 'GET',
            url: '/api/get_image_list'
        }).then(function (response) {
            // success call back
            console.log('successful request');
            console.log(response);
            scope.rowCollection = response.data;
            if (recall_func) {
                recall_func(response.data);
            }
        }, function (response) {
            console.log(response)
        });
    }

}]);

app.controller('image_list', ['$scope', '$timeout', '$http', function (scope, $timeout, $http) {
    scope.rowCollection = [];
    scope.confirmed = 0;
    scope.class_confirmed = 'active';
    scope.class_unconfirmed = '';
    scope.page_num = 1;
    scope.degree_desp = {0: '无病变', 1: '疑似病变', 2: '有病变', 1000: '眼科就诊详查'};
    scope.level_desp = {0: '未见DR', 1: '轻度NPDR', 2: '中度NPDR', 3: '重度NPDR', 4: 'PDR', 1000: '无法诊断'};
    scope.none_dr_lesion_desp = ['无', 'AMD', '视盘病变', 'RVO', 'PM', 'EMR', '其他'];
    scope.quality_desp = {0: '良好', 1: '影响诊断', 2: '无法诊断', 3: '有伪影'};
    scope.items_per_page = 10;
    scope.max_page = 1;

    scope.renew = function (recall_func) {
        console.log('updata', scope.confirmed);
        scope.get_max_page();
        if (scope.page_num > scope.max_page) {
            scope.page_num = scope.max_page;
        }
        $http({
            method: 'GET',
            url: '/api/check_list/' + scope.confirmed + '/' + scope.page_num + '/' + scope.items_per_page,
        }).then(function (response) {
            // success call back
            console.log('successful request');
            console.log(response);
            scope.rowCollection = response.data;
            if (recall_func) {
                recall_func(response.data);
            }
        }, function (response) {
            // err response
            console.log(response)
        });
    };
    scope.change_degree = function (index, level) {
        console.log(index + ' change to ' + level);
        if (level == scope.rowCollection[index].degree) {
            return
        }
        scope.rowCollection[index].degree = level;
        scope.rowCollection[index].changed = 1;
    };
    scope.change_level = function (index, level) {
        console.log(index + ' change to ' + level);
        if (level == scope.rowCollection[index].level) {
            return
        }
        scope.rowCollection[index].level = level;
        scope.rowCollection[index].changed = 1;
    };
    scope.change_quality = function (index, level) {
        console.log(index + ' change to ' + level);
        if (level == 2) {
            scope.change_level(index, 1000);
            scope.change_degree(index, 1000)
        }
        if (level == scope.rowCollection[index].image_quality) {
            return
        }
        scope.rowCollection[index].image_quality = level;
    };
    scope.change_none_dr = function (index, value) {
        scope.rowCollection[index].none_dr_lesion = value;
    };
    scope.confirm_result = function () {
        $http({
            method: 'POST',
            url: '/api/confirm',
            headers: {
                'Content-Type': 'application/json'
            },
            data: scope.rowCollection
        }).then(function (response) {
            // success call back
            console.log('successful request');
            console.log(response);
            alert('提交成功');
            scope.renew();
            // $scope.init();
        }, function (response) {
            console.log(response);
            alert('提交失败');
            scope.renew();
        });
    };
    scope.get_max_page = function () {
        $http({
            method: 'GET',
            url: '/api/check_list/count/' + scope.confirmed,
            headers: {
                'Content-Type': 'application/json'
            },
            data: scope.rowCollection
        }).then(function (response) {
            // success call back
            console.log('successful request');
            console.log(response);
            scope.max_page = Math.ceil(response.data.count / scope.items_per_page);
        }, function (response) {
            console.error(response);
            alert('提交失败');
            scope.renew();
        });
    };
    scope.next_page = function () {
        console.log('next');
        scope.page_num += 1;
        scope.renew(function (data) {
            if (data.length <= 0) {
                scope.page_num -= 1;
            }
        });
    };
    scope.prev_page = function () {
        console.log('prev');
        if (scope.page_num > 1) {
            scope.page_num -= 1;
        } else {
            alert("已经到第一页");
            return
        }
        scope.renew();
    };
    scope.renew();


}]);

app.controller('login', ['$scope', '$timeout', '$http', function (scope, $timeout, $http) {
    scope.user_name = '';
    scope.psw = '';
    scope.login = function () {
        $http({
            method: 'POST',
            url: '/api/get_token',
            headers: {
                'Content-Type': 'application/json'
            },
            data: {
                'user_name':scope.user_name,
                'password':scope.psw
            }
        }).then(function (response) {
            // success call back
            console.log('successful request');
            console.log(JSON.stringify(response.data));
            if (response.data['token'] !== ''){
                scope.set_token(response.data['token']);
                scope.set_menu_item('list');
            } else {
                alert(response.data['error'])
            }
        }, function (response) {
            console.log(response)
        });
    };

}]);
